from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.models import User,Permission,Group
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import permission_required


# 后台用户添加
def useradd(request):
    if request.method=="GET":
        # 查询所以组
        ga = Group.objects.all()
        context = {"group": ga}
        return render(request, "myadmin/auth/user/add.html",context)
    elif request.method == "POST":
        # 执行管理员添加
        # 判断是否是超级管理员
        if request.POST.get("is_supper") == "1":
            # 超级管理员
            ob = User.objects.create_superuser(request.POST["username"],request.POST["email"],request.POST["password"])
            ob.save()
        else:
            ob = User.objects.create_user(request.POST["username"],request.POST["email"],request.POST["password"])
            ob.save()

        prms = request.POST.getlist("prms",None)
        if prms:
            # 分配组
            ob.groups.set(prms)
            ob.save()

    return HttpResponse("<script>alert('添加成功');location.href='list'</script>")

# 后台用户列表
def userlist(request):
    ob = User.objects.all()
    centext = {"data":ob}
    return render(request, "myadmin/auth/user/list.html",centext)

# 后台用户删除
def userdel(request,uid):
    ob = User.objects.get(id=uid)
    ob.delete()
    return HttpResponse("<script>location.href='"+reverse("auth_user_list")+"'</script>")


# 后台组列表
def grouplist(request):
    ob = Group.objects.all()
    context = {"data":ob}
    # 加载模板
    return render(request, "myadmin/auth/group/list.html",context)
# 后台组添加
def groupadd(request):
    if request.method == "GET":
        # 获取所以权限
        ob = Permission.objects.all().exclude(name__contains="Can")
        context = {"parm":ob}
        # 加载模板
        return render(request, "myadmin/auth/group/add.html",context)
    else:
        prms = request.POST.getlist("prms")
        # 创建组
        g = Group(name=request.POST["name"])
        g.save()

        # 给组分配权限
        if prms:
            g.permissions.set(prms)
            g.save()

    return HttpResponse("<script>alert('添加成功');location.href='list'</script>")
# 后台组的修改
def authUpdate(request,gid):
    # 查询当前组
    group = Group.objects.get(id=int(gid))
    if request.method == "GET":
        # 查询所以权限  然后过滤掉已有权限
        ob = Permission.objects.all().exclude(name__contains="Can").exclude(group=group)
        context = {"group":group,"data":ob}
        return render(request, "myadmin/auth/group/detai.html",context)
    elif request.method == "POST":
        # 清空所以权限
        group.name = request.POST["name"]
        group.permissions.clear()
        # 获取选中所以权限
        if request.POST.getlist("prms"):
            # 给组设置选中权限
            group.permissions.set(request.POST.getlist("prms"))
        group.save()

        return HttpResponse("<script>alert('添加成功');location.href='"+reverse('auth_group_list')+"'</script>")




# 后台登录
def mylogin(request):
    if request.method == "POST":
        res = request.POST.dict()
        if res['code'] != request.session['verifycode']:
            return HttpResponse("<script>alert('验证码错误');location.href='"+reverse('myadmin_login')+"'</script>")

        username = request.POST['username']
        password = request.POST['password']
        # 获取user对象  auth中的user
        user = authenticate(request, username=username, password=password)
        if user:
            # 登录
            login(request,user)
            return HttpResponse("<script>location.href='" + reverse('myadmin_index') + "'</script>")
        return HttpResponse("<script>alert('用户名不存在');location.href='"+reverse('myadmin_login')+"'</script>")
    return render(request,'myadmin/login.html')

# 退出登录
def mylogout(request):
    logout(request)
    return HttpResponse("<script>location.href='"+reverse('myadmin_index')+"'</script>")


